package com.itheima.servlet;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 传递一个operation参数，根据此参数的名称来判断要进行什么操作
        // operation=login 则是登录
        // operation=findAll 则是查询所有

        String operation = request.getParameter("operation");
        if ("login".equals(operation)) {
            // 登录
            login(request, response);
        } else if ("findAll".equals(operation)) {
            // 查询所有
            findAll(request, response);
        }

    }

    private void findAll(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<User> list = userService.findAll();
            // 将查询结果存储到request中，转发到list.jsp
            request.setAttribute("list", list);
            // 转发回登录页面
            request.getRequestDispatcher("/list.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void login(HttpServletRequest request, HttpServletResponse response) {
        // 获取登录参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        try {
            User user = userService.login(username, password);
            if (user == null) {
                // 给出错误提示
                request.setAttribute("error", "用户名或密码错误!");
                // 转发回登录页面
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            } else {
                // 跳转到首页 list.jsp
                request.getRequestDispatcher("/list.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
